<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AVI转DICOM转换器</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        .upload-area {
            border: 2px dashed #007bff;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            background-color: white;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .upload-area:hover {
            border-color: #0056b3;
            background-color: #f8f9ff;
        }
        .upload-area.dragover {
            border-color: #28a745;
            background-color: #f8fff8;
        }
        .progress-container {
            display: none;
        }
        .file-item {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .dicom-list {
            display: none;
        }
        .dicom-item {
            background: white;
            border-radius: 8px;
            padding: 10px;
            margin-bottom: 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
    </style>
</head>
<body>
    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="text-center mb-5">
                    <h1 class="display-4 mb-3">
                        <i class="fas fa-file-video text-primary"></i>
                        AVI转DICOM转换器
                    </h1>
                    <p class="lead text-muted">将AVI视频文件转换为DICOM医学影像格式</p>
                </div>

                <!-- 上传区域 -->
                <div class="card mb-4">
                    <div class="card-body">
                        <div class="upload-area" id="uploadArea">
                            <i class="fas fa-cloud-upload-alt fa-3x text-primary mb-3"></i>
                            <h4>拖拽AVI文件到此处</h4>
                            <p class="text-muted">或点击选择文件</p>
                            <input type="file" id="fileInput" accept=".avi" multiple style="display: none;">
                        </div>
                    </div>
                </div>

                <!-- 文件列表 -->
                <div id="fileList" class="mb-4"></div>

                <!-- 进度显示 -->
                <div id="progressContainer" class="progress-container">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-spinner fa-spin"></i>
                                转换进度
                            </h5>
                        </div>
                        <div class="card-body">
                            <div id="progressList"></div>
                        </div>
                    </div>
                </div>

                <!-- DICOM文件列表 -->
                <div id="dicomList" class="dicom-list">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">
                                <i class="fas fa-file-medical"></i>
                                DICOM文件列表
                            </h5>
                            <button class="btn btn-success" id="downloadAllBtn">
                                <i class="fas fa-download"></i>
                                打包下载全部
                            </button>
                        </div>
                        <div class="card-body">
                            <div id="dicomFilesList"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script>
        class AVIToDICOMConverter {
            constructor() {
                this.tasks = new Map();
                this.initEventListeners();
            }

            initEventListeners() {
                const uploadArea = document.getElementById('uploadArea');
                const fileInput = document.getElementById('fileInput');

                uploadArea.addEventListener('click', () => fileInput.click());
                uploadArea.addEventListener('dragover', this.handleDragOver.bind(this));
                uploadArea.addEventListener('dragleave', this.handleDragLeave.bind(this));
                uploadArea.addEventListener('drop', this.handleDrop.bind(this));
                fileInput.addEventListener('change', this.handleFileSelect.bind(this));

                document.getElementById('downloadAllBtn').addEventListener('click', this.downloadAll.bind(this));
            }

            handleDragOver(e) {
                e.preventDefault();
                e.currentTarget.classList.add('dragover');
            }

            handleDragLeave(e) {
                e.currentTarget.classList.remove('dragover');
            }

            handleDrop(e) {
                e.preventDefault();
                e.currentTarget.classList.remove('dragover');
                const files = Array.from(e.dataTransfer.files).filter(f => f.name.endsWith('.avi'));
                this.processFiles(files);
            }

            handleFileSelect(e) {
                const files = Array.from(e.target.files);
                this.processFiles(files);
            }

            async processFiles(files) {
                for (const file of files) {
                    await this.uploadFile(file);
                }
            }

            async uploadFile(file) {
                const formData = new FormData();
                formData.append('file', file);

                try {
                    const response = await fetch('/upload', {
                        method: 'POST',
                        body: formData
                    });
                    const result = await response.json();

                    if (response.ok) {
                        this.addFileToList(file.name, result.task_id);
                        this.startProgressTracking(result.task_id, file.name);
                    } else {
                        this.showError(file.name, result.detail);
                    }
                } catch (error) {
                    this.showError(file.name, error.message);
                }
            }

            addFileToList(filename, taskId) {
                const fileList = document.getElementById('fileList');
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                fileItem.innerHTML = `
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <i class="fas fa-file-video text-primary"></i>
                            <strong>${filename}</strong>
                        </div>
                        <div>
                            <span class="badge bg-warning text-dark" id="status-${taskId}">等待处理</span>
                        </div>
                    </div>
                `;
                fileList.appendChild(fileItem);
            }

            startProgressTracking(taskId, filename) {
                document.getElementById('progressContainer').style.display = 'block';
                
                const progressList = document.getElementById('progressList');
                const progressItem = document.createElement('div');
                progressItem.className = 'mb-3';
                progressItem.innerHTML = `
                    <div class="d-flex justify-content-between mb-1">
                        <span>${filename}</span>
                        <span id="progress-text-${taskId}">0%</span>
                    </div>
                    <div class="progress">
                        <div class="progress-bar" id="progress-bar-${taskId}" 
                             role="progressbar" style="width: 0%"></div>
                    </div>
                `;
                progressList.appendChild(progressItem);

                this.trackProgress(taskId, filename);
            }

            async trackProgress(taskId, filename) {
                const interval = setInterval(async () => {
                    try {
                        const response = await fetch(`/progress/${taskId}`);
                        const progress = await response.json();

                        if (response.ok) {
                            this.updateProgress(taskId, progress);
                            
                            if (progress.status === 'completed') {
                                clearInterval(interval);
                                this.showDicomFiles(taskId, filename);
                            } else if (progress.status === 'error') {
                                clearInterval(interval);
                                this.showError(filename, progress.error);
                            }
                        }
                    } catch (error) {
                        console.error('获取进度失败:', error);
                    }
                }, 1000);
            }

            updateProgress(taskId, progress) {
                const progressBar = document.getElementById(`progress-bar-${taskId}`);
                const progressText = document.getElementById(`progress-text-${taskId}`);
                const statusBadge = document.getElementById(`status-${taskId}`);

                if (progressBar && progressText) {
                    const percentage = progress.progress || 0;
                    progressBar.style.width = `${percentage}%`;
                    progressBar.setAttribute('aria-valuenow', percentage);
                    progressText.textContent = `${percentage}% (${progress.current_frame}/${progress.total_frames})`;
                }

                if (statusBadge) {
                    if (progress.status === 'processing') {
                        statusBadge.className = 'badge bg-info';
                        statusBadge.textContent = '处理中';
                    } else if (progress.status === 'completed') {
                        statusBadge.className = 'badge bg-success';
                        statusBadge.textContent = '已完成';
                    } else if (progress.status === 'error') {
                        statusBadge.className = 'badge bg-danger';
                        statusBadge.textContent = '错误';
                    }
                }
            }

            async showDicomFiles(taskId, filename) {
                document.getElementById('dicomList').style.display = 'block';
                
                try {
                    const response = await fetch(`/list-files/${taskId}`);
                    const data = await response.json();
                    
                    const dicomFilesList = document.getElementById('dicomFilesList');
                    dicomFilesList.innerHTML = '';

                    data.files.forEach(file => {
                        const item = document.createElement('div');
                        item.className = 'dicom-item';
                        item.innerHTML = `
                            <span><i class="fas fa-file-medical text-primary"></i> ${file}</span>
                            <button class="btn btn-sm btn-primary" onclick="converter.downloadFile('${taskId}', '${file}')">
                                <i class="fas fa-download"></i> 下载
                            </button>
                        `;
                        dicomFilesList.appendChild(item);
                    });

                    // 设置打包下载按钮
                    document.getElementById('downloadAllBtn').onclick = () => {
                        window.location.href = `/download-zip/${taskId}`;
                    };
                } catch (error) {
                    console.error('获取DICOM文件列表失败:', error);
                }
            }

            downloadFile(taskId, filename) {
                window.location.href = `/download/${taskId}/${filename}`;
            }

            downloadAll() {
                // 由showDicomFiles方法设置
            }

            showError(filename, error) {
                alert(`文件 ${filename} 处理失败: ${error}`);
            }
        }

        // 初始化转换器
        const converter = new AVIToDICOMConverter();
    </script>
</body>
</html>